import React from 'react'
import {fetch, post} from '../../../my_axios/api'
import {Row, Col, Icon, Button, Table, message, Modal, Tabs, Checkbox} from 'antd'
import AddRoleForm from './component/add_role_form'
import PageTitle from '../../../components/PageTitle/index'
import PropTypes from 'prop-types'

const TabPane = Tabs.TabPane;

export default class role extends React.Component {
    // static contextTypes = {
    //     store: PropTypes.object,
    // }
    constructor(props) {
        super(props);
        this.currentRoleId = '';
        this.formType = '';
        this.state = {
            allPermission: {},
            allPermissionList:[],
            changePermissionShow: false,
            addRoleModalShow: false,
            modalDeleteShow: false,
            loading: true,
            roleList: [],
            A: '123',
            roleObject: {
                code: '',
                name: ''
            },
            tabs: [],
            defaultPermission: [],
            themeColor: '',
            buttonList: [
                {
                    type: 'primary',
                    icon: 'plus',
                    isShow: false,
                    name: '新增',
                    methodName: 'addRole'
                },
                {
                    type: 'primary',
                    icon: 'edit',
                    isShow: false,
                    name: '修改',
                    methodName: 'updateRole'
                },
                {
                    type: 'primary',
                    icon: 'eye-o',
                    isShow: false,
                    name: '读取',
                    methodName: 'getPermissions'
                },
                {
                    type: 'primary',
                    icon: 'user',
                    isShow: false,
                    name: '配置权限',
                    methodName: 'changePermissions'
                },
                {
                    type: 'warning',
                    icon: 'delete',
                    isShow: false,
                    name: '删除',
                    methodName: 'roleDelete'
                },
            ],
            indeterminate:true,
            checkAll: false,
        };

    }

    componentDidMount() {
        this.getPermissionByPath();
        this.getRoleList();
        // const {store} = this.context
        // this._updateThemeColor()
        // store.subscribe(() => this._updateThemeColor())//监听数据变化，重新渲染。如果数据变化重新调用_updateThemeColor
    }
    onCheckAllChange = (e) => {
        console.log(e.target.checked);
        this.setState({
            defaultPermission: e.target.checked ? this.state.allPermissionList : [],
            indeterminate: false,
            checkAll: e.target.checked,
        });
    };

    // _updateThemeColor() {
    //     const {store} = this.context
    //     const state = store.getState()
    //     this.setState({themeColor: state.themeColor})
    // }
    /**
     * 根据权限获取按钮
     */
    getPermissionByPath() {
        let params = {
            route: '/role/list'
        };
        fetch('permission/children', params).then(res => {
            if (res.status === 'success') {
                let list = this.state.buttonList;
                for (let permission of res.data) {
                    for (let button of this.state.buttonList) {
                        if (permission.name === button.name) {
                            if (permission.name === '读取') {
                                button.name = '查看'
                            }
                            button.isShow = true;
                        }
                    }
                }
                this.setState({
                    buttonList: list
                })
            } else {
                message.error(res.data.message);
            }

        }).catch(err => {
            console.log(err);
        })
    }

    /**
     *获取所有权限
     */
    changePermissions() {
        fetch('permission/list', {role_id: this.currentRoleId}).then(res => {
            if (res.status === 'success') {
                this.setState({
                    allPermission: res.data,
                });
                var tabs = [];
                var defaultPermission = [];
                var allPermissionList = [];

                for (let permission of this.state.allPermission.children) {
                    if (permission.checked) {
                        defaultPermission.push(permission.id)
                    }
                    allPermissionList.push(permission.id);
                    let child = [];
                    for (let per of permission.children) {
                        if (per.checked) {
                            defaultPermission.push(per.id)
                        }
                        allPermissionList.push(per.id);
                        let grandson = [];
                        for (let p of per.children) {
                            if (p.checked) {
                                defaultPermission.push(p.id)
                            }
                            allPermissionList.push(p.id);
                            grandson.push(
                                <Col xs={24} sm={12} md={12} lg={12} xl={6} key={p.id}
                                     style={{marginTop: 10, marginBottom: 10}}>
                                    <Checkbox value={p.id} checked={p.checked}
                                    >{p.name}</Checkbox>
                                </Col>
                            )
                        }
                        child.push(
                            <div key={per.id} style={{marginTop: 10, marginLeft: 10, marginBottom: 25}}>
                                <Row>
                                    <Checkbox value={per.id} checked={per.checked}
                                    >{per.name}:</Checkbox>
                                </Row>
                                <Row style={{marginLeft: 20}}>
                                    {grandson}
                                </Row>
                            </div>
                        )
                    }
                    tabs.push(
                        <TabPane tab={permission.name} key={permission.id}>
                            <Checkbox value={permission.id} checked={permission.checked}
                            >{permission.name}</Checkbox>
                            {child}
                        </TabPane>
                    )
                }
                this.setState({
                    defaultPermission: defaultPermission,
                    allPermissionList:allPermissionList,
                    tabs: tabs,
                    changePermissionShow: true,
                })
            } else {
                message.error(res.data.message);
            }

        }).catch(err => {
            console.log(err);
        })
    }

    /**
     * 角色列表
     */
    getRoleList() {
        this.setState({
            loading: true
        });
        fetch('role/list').then(res => {
            if (res.status === 'success') {
                this.setState({
                    roleList: res.data,
                    loading: false
                });
            } else {
                message.error(res.data.message);
            }

        }).catch(err => {
            console.log(err);
        })
    }

    /**
     * 根据角色ID获取角色
     */
    getRoleById() {
        fetch('role/get', {id: this.currentRoleId}).then(res => {
            if (res.status === 'success') {
                this.setState({
                    roleObject: {
                        code: res.data.code,
                        name: res.data.name
                    }
                });
                if (this.formType === '修改') {
                    this.setState({
                        addRoleModalShow: true
                    })
                } else if (this.formType === '删除') {
                    this.setState({
                        modalDeleteShow: true
                    })
                }
            } else {
                message.error(res.data.message);
            }

        }).catch(err => {
            console.log(err);
        })

    }

    /**
     * 操作按钮
     */
    buttonMethods(name) {
        if (name !== 'addRole' && (this.currentRoleId === '' || this.currentRoleId === undefined)) {
            message.error('请选择角色');
        } else {
            if (name === 'changePermissions') {
                this.formType = '配置权限';
                this.changePermissions();
            } else if (name === 'addRole') {
                this.formType = '新增';
                this.setState({
                    addRoleModalShow: true,
                    roleObject: {
                        code: '',
                        name: ''
                    }
                });

            } else if (name === 'updateRole') {
                this.formType = '修改';
                this.getRoleById();
            } else if (name === 'roleDelete') {
                this.formType = '删除';
                this.getRoleById();

            } else if (name === 'getPermissions') {
                this.formType = '查看权限';
                this.changePermissions();
            }
        }
    }

    addRoleHandleCancel() {
        this.setState({
            addRoleModalShow: false,
        });
        this.restoreData();
    }

    //调用子组件的方法
    addRoleHandleOk() {
        this.formRef.handleSubmit();

    }

    submitForm(value) {
        if (this.formType === '新增') {
            let params = {
                code: value.code,
                name: value.name
            };
            post('role/create', params).then(res => {
                if (res.status === 'success') {
                    message.success("新增成功");
                    this.setState({
                        addRoleModalShow: false
                    });
                    this.restoreData();
                    this.getRoleList();
                } else {
                    message.error(res.data.message);
                }
            }).catch(err => {
                console.log(err);
            })

        } else if (this.formType === '修改') {
            let params = {
                id: this.currentRoleId,
                code: value.code,
                name: value.name
            };
            post('role/update', params).then(res => {
                if (res.status === 'success') {
                    message.success("修改成功");
                    this.setState({
                        addRoleModalShow: false
                    });
                    this.getRoleList();
                } else {
                    message.error(res.data.message);
                }
            }).catch(err => {
                console.log(err);
            })
        }

    }

    //清空表单
    restoreData() {
        this.formRef.resetFields();
        this.setState({
            roleObject: {
                code: '',
                name: ''
            }
        })
    }

    deleteRoleHandleCancel() {
        this.setState({
            modalDeleteShow: false,
            roleObject: {
                code: '',
                name: ''
            }
        })

    }

    deleteRoleHandleOk() {
        let params = {
            id: this.currentRoleId,
        };
        post('role/delete', params).then(res => {
            if (res.status === 'success') {
                message.success("删除成功");
                this.setState({
                    modalDeleteShow: false,
                });
                this.getRoleList();
                this.currentRoleId = '';
            } else {
                message.error(res.data.message);
            }
        }).catch(err => {
            console.log(err);
        })
    }

    changePermissionShowHandleCancel() {
        this.setState({
            changePermissionShow: false
        })
    }

    changePermissionShowHandleOk() {
        let params = {
            id: this.currentRoleId,
            permissions: this.state.defaultPermission.toString()
        };
        post('role/change_permissions', params).then(res => {
            if (res.status === 'success') {
                message.success("配置成功");
                this.setState({
                    changePermissionShow: false,
                });
                this.getRoleList();
            } else {
                message.error(res.data.message);
            }
        }).catch(err => {
            console.log(err);
        });
    }

    checkboxOnChange(checkedValues) {
        this.setState({
            defaultPermission: checkedValues,
            indeterminate: !!checkedValues.length && (checkedValues.length <this.state.allPermissionList.length),
            checkAll: checkedValues.length === this.state.allPermissionList.length,
        })
    }

    onRowClick = (record, index) => {
        let selectedKey = [record.id];
        this.currentRoleId = record.id;
        this.setState({
            selectedRowKeys: selectedKey,
        });
    };

    render() {
        const selectedRowKeys = this.state.selectedRowKeys;
        const rowSelection = {
            type: 'radio',//单选
            selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.currentRoleId = `${selectedRowKeys}`;
                this.setState({
                    selectedRowKeys: selectedRowKeys,
                });
            },
        };

        return (
            <div style={{padding: 10, background: 'white'}}>
                <PageTitle
                    title="角色管理"
                    buttonMethods={this.buttonMethods.bind(this)}
                    buttonList={this.state.buttonList}
                />
                <div style={{marginTop: 40}}>
                    <Table rowSelection={rowSelection}
                           scroll={{x: 800}}
                           size='small'
                           loading={this.state.loading}
                           dataSource={this.state.roleList}
                           columns={columns}
                           onRow={(record, index) => {
                               return {
                                   onClick: () => {
                                       this.onRowClick(record, index);
                                   }
                               };
                           }}
                           rowKey="id"
                           pagination={false}
                           bordered/>
                </div>
                <Modal
                    width={477}
                    title={this.formType}
                    visible={this.state.addRoleModalShow}
                    onCancel={this.addRoleHandleCancel.bind(this)}
                    footer={[
                        <Button key="back" onClick={this.addRoleHandleCancel.bind(this)}>取消</Button>,
                        <Button key="submit" type="primary" htmlType="submit"
                                onClick={this.addRoleHandleOk.bind(this)}>
                            提交
                        </Button>
                    ]}>
                    <Row style={{paddingRight: 40}}>
                        <AddRoleForm wrappedComponentRef={(inst) => this.formRef = inst}
                                     roleObject={this.state.roleObject} addRoleCallback={this.submitForm.bind(this)}>
                        </AddRoleForm>
                    </Row>

                </Modal>
                <Modal
                    width={500}
                    title='删除'
                    visible={this.state.modalDeleteShow}
                    onCancel={this.deleteRoleHandleCancel.bind(this)}
                    footer={[
                        <Button key="back" onClick={this.deleteRoleHandleCancel.bind(this)}>取消</Button>,
                        <Button key="submit" type="primary" htmlType="submit"
                                onClick={this.deleteRoleHandleOk.bind(this)}>
                            删除
                        </Button>,
                    ]}>
                    <div className="delete_user_box">
                        <div className="delete_user_name">角色名称：
                            <span>{this.state.roleObject.name}</span>
                        </div>
                        <div className="delete_user_name">角色编号：
                            <span>{this.state.roleObject.code}</span>
                        </div>
                    </div>
                </Modal>
                <Modal
                    width='70%'
                    visible={this.state.changePermissionShow}
                    onCancel={this.changePermissionShowHandleCancel.bind(this)}
                    footer={
                        this.formType !== "查看权限" ? [
                            <Row key="row">
                                <Col span={12} style={{textAlign:'left'}} key="全选">
                                    <Checkbox
                                        indeterminate={this.state.indeterminate}
                                        onChange={this.onCheckAllChange}
                                        checked={this.state.checkAll}
                                    >
                                        全选
                                    </Checkbox>
                                </Col>
                                <Col span={12} key="按钮">
                                    <Button key="back" onClick={this.changePermissionShowHandleCancel.bind(this)}>取消</Button>
                                    <Button key="submit" type="primary" htmlType="submit"
                                            onClick={this.changePermissionShowHandleOk.bind(this)}>
                                        确认
                                    </Button>
                                </Col>
                            </Row>

                        ] : null
                    }
                >
                    <Row>
                        <Checkbox.Group style={{width: '100%'}} onChange={this.checkboxOnChange.bind(this)}
                                        value={this.state.defaultPermission}>
                            <Tabs style={{marginTop: 15, overflow: 'scroll', height: 500, overflowX: 'hidden'}}>
                                {this.state.tabs}
                            </Tabs>
                        </Checkbox.Group>
                    </Row>
                </Modal>
            </div>
        )
    }
}
const columns = [
    {
        title: '编号',
        dataIndex: 'code',
        key: 'code',
    }, {
        title: '名称',
        dataIndex: 'name',
        key: 'name',
    }, {
        title: '创建时间',
        dataIndex: 'created_at',
        key: 'created_at',
    },
];
